package homework5.test;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author fengq
 */
public class SocketServer {
    public void setSocketServer(){
        ServerSocket serverSocket=null;
        try {
            serverSocket = new ServerSocket(8800);
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String info=null;
            while(!((info=bufferedReader.readLine())==null)){
                System.out.println("是服务器，客户登陆信息为："+info);
            }
            System.out.println("服务器创建完成");
            String reply="你爱我，我爱你，蜜雪冰城甜蜜蜜";
            outputStream.write(reply.getBytes());
            outputStream.close();
            inputStream.close();
            bufferedReader.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//    public static void main(String[] args) {
//        new SocketServer().setSocketServer();
//    }


    public static void main(String[] args) throws IOException {
        //建立一个服务器Socket(ServerSocket),指定端口8800并开始监听
        ServerSocket serverSocket = new ServerSocket(8800);
        //使用accept()方法等待客户端发起通信
        Socket socket = serverSocket.accept();
        //打开输入/输出流
        InputStream is = socket.getInputStream();
        OutputStream os = socket.getOutputStream();
        //获取客户端信息，即从输入流读取信息
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String info = null;
        while(!((info=br.readLine())==null)) {
            System.out.println("我是服务器，客户登录信息为："+info);
        }
        //给客户端一个响应，即向输出流中写入信息
        String reply = "欢迎你，登录成功！";
        os.write(reply.getBytes());
        socket.close();
        serverSocket.close();

    }
}
